/*
 * Create in 2012-12-3 下午10:26:05.
 */
package kit4j.app.notepad.ui.menu;

import java.awt.Menu;
import java.awt.MenuItem;
import java.util.HashMap;
import java.util.Map;

import kit4j.app.notepad.command.NotepadCommandExecutor;
import kit4j.app.notepad.config.NotepadConfig;
import kit4j.app.notepad.factory.NotepadFactory;
import kit4j.app.notepad.factory.listener.NotepadFactoryListener;
import kit4j.app.notepad.ui.window.Notepad;

/**
 * 
 * @author MiniKnife
 * 
 */
public class NotepadsMenu extends Menu {

	private static final long serialVersionUID = -1146586817594516725L;

	private ShowAllNotepadMenuItem showAllNotepadMenuItem;

	private Map<Notepad, Menu> notepadMenuByNotepad;

	public NotepadsMenu(NotepadConfig config, NotepadCommandExecutor commandExecutor) {
		super(config.getString("MENU.NOTEPADS_LABEL", "Notepads..."));
		installNotepadFactoryListener(config);
		
		notepadMenuByNotepad = new HashMap<Notepad, Menu>();
		showAllNotepadMenuItem = new ShowAllNotepadMenuItem(config, commandExecutor);
		
		add(showAllNotepadMenuItem);
	}

	private void installNotepadFactoryListener(final NotepadConfig config) {
		NotepadFactory.getInstance().addNotepadFactoryListener(new NotepadFactoryListener() {

			@Override
			public void notepadShowed(Notepad notepad) {
				Menu notepadMenu = new NotepadMenu(config, notepad, 1);
				notepadMenuByNotepad.put(notepad, notepadMenu);
				NotepadsMenu.this.insert(notepadMenu, 1);
				resetShowNotepadMenuItemIndex();
			}

			@Override
			public void notepadFreed(Notepad notepad) {
				MenuItem showNotepadMenuItem = notepadMenuByNotepad.get(notepad);
				NotepadsMenu.this.remove(showNotepadMenuItem);
				resetShowNotepadMenuItemIndex();
			}
		});
	}
	
	private void resetShowNotepadMenuItemIndex() {
		int count = getItemCount();
		
		for(int i = 0, notepadIndex = 1; i < count; ++i) {
			MenuItem menu = getItem(i);
			if(menu instanceof NotepadMenu) {
				((NotepadMenu) menu).setNotepadIndex(notepadIndex);
				++notepadIndex;
			}
		}
	}

}
